﻿namespace Practices.SharePoint.Identity.WebControls {
    using Microsoft.IdentityModel.Claims;
    using Microsoft.SharePoint.Utilities;
    using Microsoft.SharePoint.WebControls;
    using System;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    
    public partial class SiteWelcome : UserControl {
        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);
            if (HttpContext.Current.User.Identity.IsAuthenticated) {
                this.ExplicitLogout.Visible = true;
                IClaimsPrincipal principal = Page.User as IClaimsPrincipal;
                if (principal != null) {
                    IClaimsIdentity identity = (IClaimsIdentity)principal.Identity;
                    string displayName = (from claim in identity.Claims
                                       where claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/displayname"
                                       select claim.Value).FirstOrDefault();
                    if (!string.IsNullOrEmpty(displayName)) {
                        PostCacheSubstitutionText p = ExplicitLogout.MenuControl.Controls[0] as PostCacheSubstitutionText;
                        if (p != null) {
                            p.PrefixHtml = string.Format("{0} {1}<!--", p.PrefixHtml, displayName);
                            p.SuffixHtml = string.Format("--> {0}", p.SuffixHtml);
                        }
                    }
                }
                return;
            }
            this.ExplicitLogin.Visible = true;
            if (SPUtility.IsCompatibilityLevel15Up) {
                this.ExplicitLogin.Attributes.CssStyle.Add("display", "inline-block");
                this.ExplicitLogin.CssClass = "ms-signInLink";
                return;
            }
            this.ExplicitLogin.Attributes.CssStyle.Add("display", "inline");
            this.ExplicitLogin.CssClass = "s4-signInLink";
        }
    }
}